package com.dillon.acr.utils

import android.Manifest.permission.ACCESS_NETWORK_STATE
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.ScanResult
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.net.wifi.WifiManager.WifiLock
import androidx.annotation.RequiresPermission


@Suppress("DEPRECATION")
@SuppressLint("MissingPermission")
//Android 8.0+无法直接获取SSID即wifi名称，获取的前提是开启定位权限

class WifiUtils(context: Context) {
    private var myContext: Context = context
    private val wifiManager: WifiManager =
        context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
    private val cm =
        myContext.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    //手机锁屏后，阻止WIFI也进入睡眠状态及WIFI的关闭
    private var wifiLock: WifiLock? = null

    //识别的wifi列表  包括接入的地址、名称、身份认证、频率、信号强度等
    val wifiScanList: List<ScanResult> = wifiManager.scanResults

    //已配置好的wifi列表，描述WIFI的链接信息，包括SSID、SSID隐藏、password
    var wifiOkList: List<WifiConfiguration>? = wifiManager.configuredNetworks

    //当前连接wifi的信息
    val wifiInfo: WifiInfo? = wifiManager.connectionInfo

    //当前连接wifi的名称SSID
    val wifiSSID: String? = wifiInfo?.ssid?.replace("\"","")

    //当前连接wifi的networkId
    val wifiNetworkID: Int = wifiInfo?.networkId ?: 0

    //当前连接wifi的IP地址
    val wificonnectedIPAddress: Int = wifiInfo?.ipAddress ?: 0

    //当前连接wifi的MAC地址
    val wifiMacAddress: String? = wifiInfo?.macAddress

    //WIFI状态
    val wifiState: Int = wifiManager.wifiState

    //开启WIFI
    fun openWifi() {
        if (!wifiManager.isWifiEnabled) {
            wifiManager.isWifiEnabled = true
        }
    }

    //关闭WIFI
    fun closeWifi() {
        if (wifiManager.isWifiEnabled) {
            wifiManager.isWifiEnabled = false
        }
    }

    //创建wifiLock
    fun createWifiLock(lockName: String) {
        wifiLock = wifiManager.createWifiLock(lockName)
    }

    //锁定wifiLock
    fun acquireWifiLock() {
        if (wifiLock != null) {
            wifiLock!!.acquire()
        }
    }

    //解锁wifiLock
    fun releaseWifiLock() {
        if (wifiLock != null && wifiLock!!.isHeld) {//判定是否锁定
            wifiLock!!.release()
        }
    }

    //先判断是否连接了wifi
    @RequiresPermission(ACCESS_NETWORK_STATE)
    fun isWifiConnected(): Boolean {
        val ni = cm.activeNetworkInfo
        return ni != null && ni.type == ConnectivityManager.TYPE_WIFI
    }
}